package com.jacob.cloud.mall.categoryproduct.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jacob.cloud.mall.categoryproduct.model.dao.ProductMapper;
import com.jacob.cloud.mall.categoryproduct.model.pojo.Product;
import com.jacob.cloud.mall.categoryproduct.model.query.ProductListQuery;
import com.jacob.cloud.mall.categoryproduct.model.request.AddProductReq;
import com.jacob.cloud.mall.categoryproduct.model.request.ProductListReq;
import com.jacob.cloud.mall.categoryproduct.model.request.UpdateProductReq;
import com.jacob.cloud.mall.categoryproduct.model.vo.CategoryVO;
import com.jacob.cloud.mall.categoryproduct.service.ICategoryService;
import com.jacob.cloud.mall.categoryproduct.service.IProductService;
import com.jacob.cloud.mall.common.common.Constant;
import com.jacob.cloud.mall.common.exception.MallException;
import com.jacob.cloud.mall.common.exception.MallExceptionEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ICategoryService categoryService;

    /**
     * 新增商品
     * @param addProductReq 商品信息
     */
    @Override
    public void add(AddProductReq addProductReq) {
        Product productOld = productMapper.selectByName(addProductReq.getName());
        // 校验商品名称是否已存在
        if (!(productOld == null)) {
            throw new MallException(MallExceptionEnum.PRODUCT_NAME_EXIST);
        }
        Product product = new Product();
        BeanUtils.copyProperties(addProductReq, product);

        int count = productMapper.insertSelective(product);
        if (count == 0) {
            throw new MallException(MallExceptionEnum.INSERT_FAIL);
        }
    }

    /**
     * 更新商品
     * @param updateProductReq 商品信息
     */
    @Override
    public void update(UpdateProductReq updateProductReq) {
        Product product = new Product();
        BeanUtils.copyProperties(updateProductReq, product);

        // 判断商品id是否存在
        Product pro = productMapper.selectByPrimaryKey(product.getId());
        if (pro == null) {
            throw new MallException(MallExceptionEnum.PRODUCT_NOT_EXIST);
        }

        // 判断商品名称是否存在
        Product productOld = productMapper.selectByName(product.getName());
        if (!(productOld == null) && !product.getId().equals(productOld.getId())) {
            throw new MallException(MallExceptionEnum.PRODUCT_NAME_EXIST);
        }

        int count = productMapper.updateByPrimaryKeySelective(product);
        if (count == 0) {
            throw new MallException(MallExceptionEnum.UPDATE_FAIL);
        }
    }

    /**
     * 根据id删除商品
     * @param productId 商品id
     */
    @Override
    public void delete(Integer productId) {
        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null) {
            throw new MallException(MallExceptionEnum.PRODUCT_NOT_EXIST);
        }
        int count = productMapper.deleteByPrimaryKey(productId);
        
        if (count == 0) {
            throw new MallException(MallExceptionEnum.DELETE_FAIL);
        }
    }

    /**
     * 批量上下架
     * @param ids        商品id数组
     * @param sellStatus 上下架状态
     */
    @Override
    public void batchUpdateSellStatus(Integer[] ids, Integer sellStatus) {
        productMapper.batchUpdateSellStatus(ids, sellStatus);
    }

    /**
     * 后台商品列表
     * @param pageSize 分页大小
     * @param pageNum  页码
     * @return 包含分页数据的分页对象
     */
    @Override
    public PageInfo<Product> listForAdmin(Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = productMapper.selectList();
        return new PageInfo<Product>(productList);
    }

    /**
     * 前台商品列表
     * @param productListReq
     */
    @Override
    public PageInfo<Product> listForCustomer(ProductListReq productListReq) {
        ProductListQuery productListQuery = new ProductListQuery();

        // 搜索处理
        if (!StringUtils.isEmpty(productListReq.getKeyword())) {
            String keyword = new StringBuilder().append("%").append(productListReq.getKeyword()).append("%").toString();
            productListQuery.setKeyword(keyword);
        }

        // 目录处理
        if (!(productListReq.getCategoryId() == null)) {
            List<CategoryVO> categoryVOS = categoryService.listCategoryForCustomer(productListReq.getCategoryId());
            ArrayList<Integer> categoryIds = new ArrayList<>();
            categoryIds.add(productListReq.getCategoryId());
            getCategoryIds(categoryVOS, categoryIds);
            productListQuery.setCategoryIds(categoryIds);
        }

        // 排序处理
        String orderBy = productListReq.getOrderBy();
        if (Constant.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)) {
            PageHelper.startPage(productListReq.getPageNum(), productListReq.getPageSize(), orderBy);
        } else {
            PageHelper.startPage(productListReq.getPageNum(), productListReq.getPageSize());
        }

        List<Product> products = productMapper.selectListForCustomer(productListQuery);
        return new PageInfo<Product>(products);
    }

    /**
     * 商品详情
     * @param id 商品id
     * @return 商品对象
     */
    @Override
    public Product detail(Integer id) {
        Product product = productMapper.selectByPrimaryKey(id);
        if (product == null) {
            throw new MallException(MallExceptionEnum.PRODUCT_NOT_EXIST);
        }
        return product;
    }

    /**
     * 获取categoryVOList中包含子节点的所有categoryId
     * @param categoryVOList 需要获取的categoryVOList
     * @param categoryIds 获取到的所有categoryId
     */
    private void getCategoryIds(List<CategoryVO> categoryVOList, ArrayList<Integer> categoryIds) {
        for (int i = 0; i < categoryVOList.size(); i++) {
            CategoryVO categoryVO = categoryVOList.get(i);
            if (!(categoryVO == null)) {
                categoryIds.add(categoryVO.getId());
                getCategoryIds(categoryVO.getChildCategory(), categoryIds);
            }
        }
    }

    /**
     * 商品扣库存
     * @param productId
     * @param stock
     */
    @Override
    public void updateStock(Integer productId, Integer stock){
        Product product = new Product();
        product.setId(productId);
        product.setStock(stock);
        productMapper.updateByPrimaryKeySelective(product);
    }


}
